package com.oly.cms.user.filter;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.grace.common.constant.CacheConstants;
import com.grace.common.constant.Constants;
import com.grace.common.enums.SysConfigGroups;
import com.grace.common.utils.MessageUtils;
import com.grace.common.utils.StringUtils;
import com.grace.redis.utils.RedisCache;
import com.grace.system.service.impl.SysSearchConfigServiceImpl;
import com.oly.cms.general.manager.WebAsyncManager;
import com.oly.cms.user.manager.factory.HandAsyncFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class WebCaptchaAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
 
     @Autowired
    private SysSearchConfigServiceImpl configService;

    @Autowired
    private RedisCache redisCache;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("attemptAuthentication"+request.getRequestURI());
        // 获取验证code
        String validateCode = request.getParameter("code");
        
        // 获取uuID
        String validateUuid = request.getParameter("uuid");

        // 获取uuID
        String username = request.getParameter("username");

        String password = request.getParameter("password");
   
        
        // 验证开关
        boolean captchaEnabled = configService.selectCaptchaEnabled(SysConfigGroups.SYS_CONFIG.getValue());
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(username, validateCode, validateUuid);
        }
        validateCaptcha(username,validateCode,validateUuid);
        // 创建 Authentication 对象
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
 
    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        //redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            WebAsyncManager.me().execute(HandAsyncFactory.recordLogininfor(username, "admin",Constants.LOGIN_FAIL,
                    MessageUtils.message("user.jcaptcha.expire")));
            throw new AccountExpiredException("验证码已经过期");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            WebAsyncManager.me().execute(HandAsyncFactory.recordLogininfor(username,"admin", Constants.LOGIN_FAIL,
                    MessageUtils.message("user.jcaptcha.error")));
            throw new CredentialsExpiredException("验证码错误");
        }
    }
}